#ifndef VRP_VELOCITY_BUFFER
#define VRP_VELOCITY_BUFFER


float4x4 _PreviousGPUViewProjection;
float2 _PreviousJitterOffset;
float2 _CurrentJutterOffset;

struct Attributes
{
    float4 positionOS   : POSITION;
    float2 uv           : TEXCOORD0;
};
struct v2f_velocity
{
    float4 pos : SV_POSITION;
    float3 vertexPos : TEXCOORD0;
    float3 worldPos : TEXCOORD1;
    float4 screenPos : TEXCOORD2;
};

v2f_velocity vert_velocity(Attributes i)
{
    v2f_velocity output;
    output.pos = TransformObjectToHClip(i.positionOS.xyz);
    output.vertexPos = i.positionOS;
    output.worldPos = TransformObjectToWorld(i.positionOS.xyz);
    output.screenPos = ComputeScreenPos(output.pos);
    return output;
}
float2 frag_velocity(v2f_velocity i) : SV_TARGET
{
    i.screenPos /= i.screenPos.w;
    
    float3 worldPos = mul(unity_MatrixPreviousM, float4(i.vertexPos.xyz, 1));
    if(unity_MotionVectorsParams.y == 0)
        worldPos = i.worldPos;

    
    float4 pClip = mul(_PreviousGPUViewProjection, float4(worldPos.xyz, 1));
    pClip /= pClip.w;
    float2 currentScreenPos = i.screenPos;
    
    float2 previousScreenPos = pClip * .5 + .5;
   
    previousScreenPos += _PreviousJitterOffset * float2(1, 1) * (_ScreenParams.zw - 1);
    currentScreenPos += _CurrentJutterOffset * float2(1, 1) * (_ScreenParams.zw - 1);
    return (currentScreenPos - previousScreenPos);
}
// float2 backgroundVelocityBuffer(v2f_ray i) : SV_TARGET
//     {
//         float3 ray = normalize(i.ray);
//
//         float depth = tex2D(_CameraDepthTex, i.uv.xy);
//         float4 worldPos;
//         if(depth <= 0)
//             worldPos = float4(ray.xyz, 0);
//         else
//             worldPos = float4(depthToWorldPos(i.uv, depth, ray), 1);
//
//         float4 previousP = mul(_PreviousGPUViewProjection, worldPos);
//         float4 currentP = mul(UNITY_MATRIX_VP, worldPos);
//         previousP/= previousP.w;
//         currentP /= currentP.w;
//         currentP.y *= _ProjectionParams.x;
//         float2 previousScreenPos = previousP.xy * .5 + .5;
//         float2 currentScreenPos = currentP.xy * .5 + .5;
//         previousScreenPos += _PreviousJitterOffset * (_ScreenParams.zw - 1);
//         currentScreenPos += _CurrentJutterOffset * (_ScreenParams.zw - 1);
//
//         return currentScreenPos - previousScreenPos;
//     }
#endif